from src.vobjects.player import Player
from src.vobjects.video import Video
from src.vobjects.item import Item

import json

class UserPlaylist:

    def __init__(self, name: str="", videos: list=[]):
        self.name = name
        self.videos = videos

    def get_video_index(self, video: Video):
        for i in range(0, len(self.videos)):
            if video.videoId == self.videos[i].videoId: return i

    def play(self, video: Video, play_option: str="", mirror: str=""):
        player = Player()
        index = self.get_video_index(video)
        ln = len(self.videos)
        videos = self.videos[index : ln]
        player.play_playlist(mirror, play_option, videos)

    def insert(self, video):
        self.videos.append(video)

    def remove(self, video):
        for vid in self.videos:
            if vid.videoId == video.videoId:
                return self.videos.remove(vid)

    def to_item(self):
        return Item(title=self.name, fstr=f"{len(self.videos)} videos", parent=self)

    def to_dict(self, dct):
        dct = {
            'name' : self.name,
            'videos' : self.videos
        }
        
        return dct

    @staticmethod
    def from_dict(dct):
        return UserPlaylist(name=dct['name'], videos=dct['videos'])

    @staticmethod
    def from_str(name: str, string: str):
        try:
            name = name
            videos_text = string.replace("\"", "`")
            videos_text = videos_text.replace("\'", "\"")
            videos_uncode = json.loads(videos_text)
            videos = []
            for vid in videos_uncode:
                video = Video().from_history_dict(vid)
                videos.append(video)
            playlist = UserPlaylist(name, videos)
        except: return None

        return playlist
